<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlref - Perl references and nested data structures - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlref">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlref.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlref">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlref">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlref">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlref">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlref">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlref">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlref">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlref">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlref">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlref">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlref">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlref">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlref">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlref">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlref">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlref">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlref">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlref">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlref">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlref">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlref">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlref">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlref">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlref">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlref">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlref">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlref">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlref">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlref">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlref">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlref">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlref">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlref">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlref">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlref">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlref">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlref">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlref">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlref">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlref">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlref">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlref">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlref">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlref">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlref">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlref">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlref">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlref">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlref">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlref">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlref">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlref">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlref">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlref">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlref">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlref">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlref">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlref">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlref">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlref">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlref">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlref">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlref">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlref">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlref">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlref">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlref">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlref">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlref">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlref">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlref">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlref">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlref">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlref">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlref">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlref">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlref">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlref">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlref">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlref">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlref.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlref">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlref">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlref">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlref">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlref">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlref">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlref">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlref">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlref">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlref">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlref">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlref">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlref">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlref">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlref">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlref">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlref">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlref">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlref">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlref">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlref">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlref">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlref">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlref">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlref">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlref">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlref">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlref">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlref">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlref">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlref">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlref">5.35.1</a>
          <a class="dropdown-item active" href="perlref.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlref.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlref.html">perlref</a>
          <div id="more">
            (<a href="perlref.txt">source</a>,
            <a href="https://metacpan.org/pod/perlref">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlref.html#NAME">NAME     </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#NOTE">NOTE</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlref.html#Making-References">Making References  </a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlref.html#Backslash-Operator">Backslash Operator  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Square-Brackets">Square Brackets        </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Curly-Brackets">Curly Brackets         </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Anonymous-Subroutines">Anonymous Subroutines       </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Constructors">Constructors  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Autovivification">Autovivification </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Typeglob-Slots">Typeglob Slots  </a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Using-References">Using References   </a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlref.html#Simple-Scalar">Simple Scalar</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Block">Block</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Arrow-Notation">Arrow Notation</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Objects">Objects</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Miscellaneous-Usage">Miscellaneous Usage</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Circular-References">Circular References  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Symbolic-references">Symbolic references    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Not-so-symbolic-references">Not-so-symbolic references</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Pseudo-hashes:-Using-an-array-as-a-hash">Pseudo-hashes: Using an array as a hash   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Function-Templates">Function Templates        </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Postfix-Dereference-Syntax">Postfix Dereference Syntax</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Postfix-Reference-Slicing">Postfix Reference Slicing</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Assigning-to-References">Assigning to References</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#Declaring-a-Reference-to-a-Variable">Declaring a Reference to a Variable</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#WARNING:-Don&#39;t-use-references-as-hash-keys">WARNING: Don&#39;t use references as hash keys  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlref.html#SEE-ALSO">SEE ALSO</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlref.html#NAME">#</a>NAME     </h1>

<p>perlref - Perl references and nested data structures</p>

<h1 id="NOTE"><a class="permalink" href="perlref.html#NOTE">#</a>NOTE</h1>

<p>This is complete documentation about all aspects of references. For a shorter, tutorial introduction to just the essential features, see <a href="perlreftut.html">perlreftut</a>.</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlref.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>Before release 5 of Perl it was difficult to represent complex data structures, because all references had to be symbolic--and even then it was difficult to refer to a variable instead of a symbol table entry. Perl now not only makes it easier to use symbolic references to variables, but also lets you have &quot;hard&quot; references to any piece of data or code. Any scalar may hold a hard reference. Because arrays and hashes contain scalars, you can now easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on.</p>

<p>Hard references are smart--they keep track of reference counts for you, automatically freeing the thing referred to when its reference count goes to zero. (Reference counts for values in self-referential or cyclic data structures may not go to zero without a little help; see <a href="perlref.html#Circular-References">&quot;Circular References&quot;</a> for a detailed explanation.) If that thing happens to be an object, the object is destructed. See <a href="perlobj.html">perlobj</a> for more about objects. (In a sense, everything in Perl is an object, but we usually reserve the word for references to objects that have been officially &quot;blessed&quot; into a class package.)</p>

<p>Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The <code>*glob</code> notation is something of a symbolic reference. (Symbolic references are sometimes called &quot;soft references&quot;, but please don&#39;t call them that; references are confusing enough without useless synonyms.)    </p>

<p>In contrast, hard references are more like hard links in a Unix file system: They are used to access an underlying object without concern for what its (other) name is. When the word &quot;reference&quot; is used without an adjective, as in the following paragraph, it is usually talking about a hard reference.  </p>

<p>References are easy to use in Perl. There is just one overriding principle: in general, Perl does no implicit referencing or dereferencing. When a scalar is holding a reference, it always behaves as a simple scalar. It doesn&#39;t magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it.</p>

<h2 id="Making-References"><a class="permalink" href="perlref.html#Making-References">#</a><a id="Making"></a>Making References  </h2>

<p>References can be created in several ways.</p>

<h3 id="Backslash-Operator"><a class="permalink" href="perlref.html#Backslash-Operator">#</a><a id="Backslash"></a>Backslash Operator  </h3>

<p>By using the backslash operator on a variable, subroutine, or value. (This works much like the &amp; (address-of) operator in C.) This typically creates <i>another</i> reference to a variable, because there&#39;s already a reference to the variable in the symbol table. But the symbol table reference might go away, and you&#39;ll still have the reference that the backslash returned. Here are some examples:</p>

<pre><code>$scalarref = \$foo;
$arrayref  = \@ARGV;
$hashref   = \%ENV;
$coderef   = \&amp;handler;
$globref   = \*foo;</code></pre>

<p>It isn&#39;t possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the <code>*foo{THING}</code> syntax below. However, you can still use type globs and globrefs as though they were IO handles.</p>

<h3 id="Square-Brackets"><a class="permalink" href="perlref.html#Square-Brackets">#</a><a id="Square"></a>Square Brackets        </h3>

<p>A reference to an anonymous array can be created using square brackets:</p>

<pre><code>$arrayref = [1, 2, [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]];</code></pre>

<p>Here we&#39;ve created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, <code>$arrayref-&gt;[2][1]</code> would have the value &quot;b&quot;.)</p>

<p>Taking a reference to an enumerated list is not the same as using square brackets--instead it&#39;s the same as creating a list of references!</p>

<pre><code>@list = (\$a, \@b, \%c);
@list = \($a, @b, %c);      # same thing!</code></pre>

<p>As a special case, <code>\(@foo)</code> returns a list of references to the contents of <code>@foo</code>, not a reference to <code>@foo</code> itself. Likewise for <code>%foo</code>, except that the key references are to copies (since the keys are just strings rather than full-fledged scalars).</p>

<h3 id="Curly-Brackets"><a class="permalink" href="perlref.html#Curly-Brackets">#</a><a id="Curly"></a>Curly Brackets         </h3>

<p>A reference to an anonymous hash can be created using curly brackets:</p>

<pre><code>$hashref = {
    &#39;Adam&#39;  =&gt; &#39;Eve&#39;,
    &#39;Clyde&#39; =&gt; &#39;Bonnie&#39;,
};</code></pre>

<p>Anonymous hash and array composers like these can be intermixed freely to produce as complicated a structure as you want. The multidimensional syntax described below works for these too. The values above are literals, but variables and expressions would work just as well, because assignment operators in Perl (even within local() or my()) are executable statements, not compile-time declarations.</p>

<p>Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a <code>+</code> or a <code>return</code> in front so that Perl realizes the opening brace isn&#39;t starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.</p>

<p>For example, if you wanted a function to make a new hash and return a reference to it, you have these options:</p>

<pre><code>sub hashem {        { @_ } }   # silently wrong
sub hashem {       +{ @_ } }   # ok
sub hashem { return { @_ } }   # ok</code></pre>

<p>On the other hand, if you want the other meaning, you can do this:</p>

<pre><code>sub showem {        { @_ } }   # ambiguous (currently ok,
                               # but may change)
sub showem {       {; @_ } }   # ok
sub showem { { return @_ } }   # ok</code></pre>

<p>The leading <code>+{</code> and <code>{;</code> always serve to disambiguate the expression to mean either the HASH reference, or the BLOCK.</p>

<h3 id="Anonymous-Subroutines"><a class="permalink" href="perlref.html#Anonymous-Subroutines">#</a><a id="Anonymous"></a>Anonymous Subroutines       </h3>

<p>A reference to an anonymous subroutine can be created by using <code>sub</code> without a subname:</p>

<pre><code>$coderef = sub { print &quot;Boink!\n&quot; };</code></pre>

<p>Note the semicolon. Except for the code inside not being immediately executed, a <code>sub {}</code> is not so much a declaration as it is an operator, like <code>do{}</code> or <code>eval{}</code>. (However, no matter how many times you execute that particular line (unless you&#39;re in an <code>eval(&quot;...&quot;)</code>), $coderef will still have a reference to the <i>same</i> anonymous subroutine.)</p>

<p>Anonymous subroutines act as closures with respect to my() variables, that is, variables lexically visible within the current scope. Closure is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it&#39;s called outside the context.</p>

<p>In human terms, it&#39;s a funny way of passing arguments to a subroutine when you define it as well as when you call it. It&#39;s useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl already provides a different mechanism to do that--see <a href="perlobj.html">perlobj</a>.</p>

<p>You might also think of closure as a way to write a subroutine template without using eval(). Here&#39;s a small example of how closures work:</p>

<pre><code>sub newprint {
    my $x = shift;
    return sub { my $y = shift; print &quot;$x, $y!\n&quot;; };
}
$h = newprint(&quot;Howdy&quot;);
$g = newprint(&quot;Greetings&quot;);

# Time passes...

&amp;$h(&quot;world&quot;);
&amp;$g(&quot;earthlings&quot;);</code></pre>

<p>This prints</p>

<pre><code class="plaintext">Howdy, world!
Greetings, earthlings!</code></pre>

<p>Note particularly that $x continues to refer to the value passed into newprint() <i>despite</i> &quot;my $x&quot; having gone out of scope by the time the anonymous subroutine runs. That&#39;s what a closure is all about.</p>

<p>This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with.</p>

<h3 id="Constructors"><a class="permalink" href="perlref.html#Constructors">#</a>Constructors  </h3>

<p>References are often returned by special subroutines called constructors. Perl objects are just references to a special type of object that happens to know which package it&#39;s associated with. Constructors are just special subroutines that know how to create that association. They do so by starting with an ordinary reference, and it remains an ordinary reference even while it&#39;s also being an object. Constructors are often named <code>new()</code>. You <i>can</i> call them indirectly:</p>

<pre><code>$objref = new Doggie( Tail =&gt; &#39;short&#39;, Ears =&gt; &#39;long&#39; );</code></pre>

<p>But that can produce ambiguous syntax in certain cases, so it&#39;s often better to use the direct method invocation approach:</p>

<pre><code>$objref   = Doggie-&gt;new(Tail =&gt; &#39;short&#39;, Ears =&gt; &#39;long&#39;);

use Term::Cap;
$terminal = Term::Cap-&gt;Tgetent( { OSPEED =&gt; 9600 });

use Tk;
$main    = MainWindow-&gt;new();
$menubar = $main-&gt;Frame(-relief              =&gt; &quot;raised&quot;,
                        -borderwidth         =&gt; 2)</code></pre>

<h3 id="Autovivification"><a class="permalink" href="perlref.html#Autovivification">#</a>Autovivification </h3>

<p>References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven&#39;t talked about dereferencing yet, we can&#39;t show you any examples yet.</p>

<h3 id="Typeglob-Slots"><a class="permalink" href="perlref.html#Typeglob-Slots">#</a><a id="Typeglob"></a>Typeglob Slots  </h3>

<p>A reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax. *foo{THING} returns a reference to the THING slot in *foo (which is the symbol table entry which holds everything known as foo).</p>

<pre><code>$scalarref = *foo{SCALAR};
$arrayref  = *ARGV{ARRAY};
$hashref   = *ENV{HASH};
$coderef   = *handler{CODE};
$ioref     = *STDIN{IO};
$globref   = *foo{GLOB};
$formatref = *foo{FORMAT};
$globname  = *foo{NAME};    # &quot;foo&quot;
$pkgname   = *foo{PACKAGE}; # &quot;main&quot;</code></pre>

<p>Most of these are self-explanatory, but <code>*foo{IO}</code> deserves special attention. It returns the IO handle, used for file handles (<a href="perlfunc.html#open">&quot;open&quot; in perlfunc</a>), sockets (<a href="perlfunc.html#socket">&quot;socket&quot; in perlfunc</a> and <a href="perlfunc.html#socketpair">&quot;socketpair&quot; in perlfunc</a>), and directory handles (<a href="perlfunc.html#opendir">&quot;opendir&quot; in perlfunc</a>). For compatibility with previous versions of Perl, <code>*foo{FILEHANDLE}</code> is a synonym for <code>*foo{IO}</code>, though it is discouraged, to encourage a consistent use of one name: IO. On perls between v5.8 and v5.22, it will issue a deprecation warning, but this deprecation has since been rescinded.</p>

<p><code>*foo{THING}</code> returns undef if that particular THING hasn&#39;t been used yet, except in the case of scalars. <code>*foo{SCALAR}</code> returns a reference to an anonymous scalar if $foo hasn&#39;t been used yet. This might change in a future release.</p>

<p><code>*foo{NAME}</code> and <code>*foo{PACKAGE}</code> are the exception, in that they return strings, rather than references. These return the package and name of the typeglob itself, rather than one that has been assigned to it. So, after <code>*foo=*Foo::bar</code>, <code>*foo</code> will become &quot;*Foo::bar&quot; when used as a string, but <code>*foo{PACKAGE}</code> and <code>*foo{NAME}</code> will continue to produce &quot;main&quot; and &quot;foo&quot;, respectively.</p>

<p><code>*foo{IO}</code> is an alternative to the <code>*HANDLE</code> mechanism given in <a href="perldata.html#Typeglobs-and-Filehandles">&quot;Typeglobs and Filehandles&quot; in perldata</a> for passing filehandles into or out of subroutines, or storing into larger data structures. Its disadvantage is that it won&#39;t create a new filehandle for you. Its advantage is that you have less risk of clobbering more than you want to with a typeglob assignment. (It still conflates file and directory handles, though.) However, if you assign the incoming value to a scalar instead of a typeglob as we do in the examples below, there&#39;s no risk of that happening.</p>

<pre><code>splutter(*STDOUT);          # pass the whole glob
splutter(*STDOUT{IO});      # pass both file and dir handles

sub splutter {
    my $fh = shift;
    print $fh &quot;her um well a hmmm\n&quot;;
}

$rec = get_rec(*STDIN);     # pass the whole glob
$rec = get_rec(*STDIN{IO}); # pass both file and dir handles

sub get_rec {
    my $fh = shift;
    return scalar &lt;$fh&gt;;
}</code></pre>

<h2 id="Using-References"><a class="permalink" href="perlref.html#Using-References">#</a><a id="Using"></a>Using References   </h2>

<p>That&#39;s it for creating references. By now you&#39;re probably dying to know how to use references to get back to your long-lost data. There are several basic methods.</p>

<h3 id="Simple-Scalar"><a class="permalink" href="perlref.html#Simple-Scalar">#</a><a id="Simple"></a>Simple Scalar</h3>

<p>Anywhere you&#39;d put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type:</p>

<pre><code>$bar = $$scalarref;
push(@$arrayref, $filename);
$$arrayref[0] = &quot;January&quot;;
$$hashref{&quot;KEY&quot;} = &quot;VALUE&quot;;
&amp;$coderef(1,2,3);
print $globref &quot;output\n&quot;;</code></pre>

<p>It&#39;s important to understand that we are specifically <i>not</i> dereferencing <code>$arrayref[0]</code> or <code>$hashref{&quot;KEY&quot;}</code> there. The dereference of the scalar variable happens <i>before</i> it does any key lookups. Anything more complicated than a simple scalar variable must use methods 2 or 3 below. However, a &quot;simple scalar&quot; includes an identifier that itself uses method 1 recursively. Therefore, the following prints &quot;howdy&quot;.</p>

<pre><code>$refrefref = \\\&quot;howdy&quot;;
print $$$$refrefref;</code></pre>

<h3 id="Block"><a class="permalink" href="perlref.html#Block">#</a>Block</h3>

<p>Anywhere you&#39;d put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type. In other words, the previous examples could be written like this:</p>

<pre><code>$bar = ${$scalarref};
push(@{$arrayref}, $filename);
${$arrayref}[0] = &quot;January&quot;;
${$hashref}{&quot;KEY&quot;} = &quot;VALUE&quot;;
&amp;{$coderef}(1,2,3);
$globref-&gt;print(&quot;output\n&quot;);  # iff IO::Handle is loaded</code></pre>

<p>Admittedly, it&#39;s a little silly to use the curlies in this case, but the BLOCK can contain any arbitrary expression, in particular, subscripted expressions:</p>

<pre><code>&amp;{ $dispatch{$index} }(1,2,3);      # call correct routine</code></pre>

<p>Because of being able to omit the curlies for the simple case of <code>$$x</code>, people often make the mistake of viewing the dereferencing symbols as proper operators, and wonder about their precedence. If they were, though, you could use parentheses instead of braces. That&#39;s not the case. Consider the difference below; case 0 is a short-hand version of case 1, <i>not</i> case 2:</p>

<pre><code>$$hashref{&quot;KEY&quot;}   = &quot;VALUE&quot;;       # CASE 0
${$hashref}{&quot;KEY&quot;} = &quot;VALUE&quot;;       # CASE 1
${$hashref{&quot;KEY&quot;}} = &quot;VALUE&quot;;       # CASE 2
${$hashref-&gt;{&quot;KEY&quot;}} = &quot;VALUE&quot;;     # CASE 3</code></pre>

<p>Case 2 is also deceptive in that you&#39;re accessing a variable called %hashref, not dereferencing through $hashref to the hash it&#39;s presumably referencing. That would be case 3.</p>

<h3 id="Arrow-Notation"><a class="permalink" href="perlref.html#Arrow-Notation">#</a><a id="Arrow"></a>Arrow Notation</h3>

<p>Subroutine calls and lookups of individual array elements arise often enough that it gets cumbersome to use method 2. As a form of syntactic sugar, the examples for method 2 may be written:</p>

<pre><code>$arrayref-&gt;[0] = &quot;January&quot;;   # Array element
$hashref-&gt;{&quot;KEY&quot;} = &quot;VALUE&quot;;  # Hash element
$coderef-&gt;(1,2,3);            # Subroutine call</code></pre>

<p>The left side of the arrow can be any expression returning a reference, including a previous dereference. Note that <code>$array[$x]</code> is <i>not</i> the same thing as <code>$array-&gt;[$x]</code> here:</p>

<pre><code>$array[$x]-&gt;{&quot;foo&quot;}-&gt;[0] = &quot;January&quot;;</code></pre>

<p>This is one of the cases we mentioned earlier in which references could spring into existence when in an lvalue context. Before this statement, <code>$array[$x]</code> may have been undefined. If so, it&#39;s automatically defined with a hash reference so that we can look up <code>{&quot;foo&quot;}</code> in it. Likewise <code>$array[$x]-&gt;{&quot;foo&quot;}</code> will automatically get defined with an array reference so that we can look up <code>[0]</code> in it. This process is called <i>autovivification</i>.</p>

<p>One more thing here. The arrow is optional <i>between</i> brackets subscripts, so you can shrink the above down to</p>

<pre><code>$array[$x]{&quot;foo&quot;}[0] = &quot;January&quot;;</code></pre>

<p>Which, in the degenerate case of using only ordinary arrays, gives you multidimensional arrays just like C&#39;s:</p>

<pre><code>$score[$x][$y][$z] += 42;</code></pre>

<p>Well, okay, not entirely like C&#39;s arrays, actually. C doesn&#39;t know how to grow its arrays on demand. Perl does.</p>

<h3 id="Objects"><a class="permalink" href="perlref.html#Objects">#</a>Objects</h3>

<p>If a reference happens to be a reference to an object, then there are probably methods to access the things referred to, and you should probably stick to those methods unless you&#39;re in the class package that defines the object&#39;s methods. In other words, be nice, and don&#39;t violate the object&#39;s encapsulation without a very good reason. Perl does not enforce encapsulation. We are not totalitarians here. We do expect some basic civility though.</p>

<h3 id="Miscellaneous-Usage"><a class="permalink" href="perlref.html#Miscellaneous-Usage">#</a><a id="Miscellaneous"></a>Miscellaneous Usage</h3>

<p>Using a string or number as a reference produces a symbolic reference, as explained above. Using a reference as a number produces an integer representing its storage location in memory. The only useful thing to be done with this is to compare two references numerically to see whether they refer to the same location. </p>

<pre><code>if ($ref1 == $ref2) {  # cheap numeric compare of references
    print &quot;refs 1 and 2 refer to the same thing\n&quot;;
}</code></pre>

<p>Using a reference as a string produces both its referent&#39;s type, including any package blessing as described in <a href="perlobj.html">perlobj</a>, as well as the numeric address expressed in hex. The ref() operator returns just the type of thing the reference is pointing to, without the address. See <a href="perlfunc.html#ref">&quot;ref&quot; in perlfunc</a> for details and examples of its use. </p>

<p>The bless() operator may be used to associate the object a reference points to with a package functioning as an object class. See <a href="perlobj.html">perlobj</a>.</p>

<p>A typeglob may be dereferenced the same way a reference can, because the dereference syntax always indicates the type of reference desired. So <code>${*foo}</code> and <code>${\$foo}</code> both indicate the same scalar variable.</p>

<p>Here&#39;s a trick for interpolating a subroutine call into a string:</p>

<pre><code>print &quot;My sub returned @{[mysub(1,2,3)]} that time.\n&quot;;</code></pre>

<p>The way it works is that when the <code>@{...}</code> is seen in the double-quoted string, it&#39;s evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to <code>mysub(1,2,3)</code>. So the whole block returns a reference to an array, which is then dereferenced by <code>@{...}</code> and stuck into the double-quoted string. This chicanery is also useful for arbitrary expressions:</p>

<pre><code>print &quot;That yields @{[$n + 5]} widgets\n&quot;;</code></pre>

<p>Similarly, an expression that returns a reference to a scalar can be dereferenced via <code>${...}</code>. Thus, the above expression may be written as:</p>

<pre><code>print &quot;That yields ${\($n + 5)} widgets\n&quot;;</code></pre>

<h2 id="Circular-References"><a class="permalink" href="perlref.html#Circular-References">#</a><a id="Circular"></a>Circular References  </h2>

<p>It is possible to create a &quot;circular reference&quot; in Perl, which can lead to memory leaks. A circular reference occurs when two references contain a reference to each other, like this:</p>

<pre><code>my $foo = {};
my $bar = { foo =&gt; $foo };
$foo-&gt;{bar} = $bar;</code></pre>

<p>You can also create a circular reference with a single variable:</p>

<pre><code>my $foo;
$foo = \$foo;</code></pre>

<p>In this case, the reference count for the variables will never reach 0, and the references will never be garbage-collected. This can lead to memory leaks.</p>

<p>Because objects in Perl are implemented as references, it&#39;s possible to have circular references with objects as well. Imagine a TreeNode class where each node references its parent and child nodes. Any node with a parent will be part of a circular reference.</p>

<p>You can break circular references by creating a &quot;weak reference&quot;. A weak reference does not increment the reference count for a variable, which means that the object can go out of scope and be destroyed. You can weaken a reference with the <code>weaken</code> function exported by the <a href="./Scalar::Util.html">Scalar::Util</a> module.</p>

<p>Here&#39;s how we can make the first example safer:</p>

<pre><code>use Scalar::Util &#39;weaken&#39;;

my $foo = {};
my $bar = { foo =&gt; $foo };
$foo-&gt;{bar} = $bar;

weaken $foo-&gt;{bar};</code></pre>

<p>The reference from <code>$foo</code> to <code>$bar</code> has been weakened. When the <code>$bar</code> variable goes out of scope, it will be garbage-collected. The next time you look at the value of the <code>$foo-&gt;{bar}</code> key, it will be <code>undef</code>.</p>

<p>This action at a distance can be confusing, so you should be careful with your use of weaken. You should weaken the reference in the variable that will go out of scope <i>first</i>. That way, the longer-lived variable will contain the expected reference until it goes out of scope.</p>

<h2 id="Symbolic-references"><a class="permalink" href="perlref.html#Symbolic-references">#</a><a id="Symbolic"></a>Symbolic references    </h2>

<p>We said that references spring into existence as necessary if they are undefined, but we didn&#39;t say what happens if a value used as a reference is already defined, but <i>isn&#39;t</i> a hard reference. If you use it as a reference, it&#39;ll be treated as a symbolic reference. That is, the value of the scalar is taken to be the <i>name</i> of a variable, rather than a direct link to a (possibly) anonymous value.</p>

<p>People frequently expect it to work like this. So it does.</p>

<pre><code>$name = &quot;foo&quot;;
$$name = 1;                 # Sets $foo
${$name} = 2;               # Sets $foo
${$name x 2} = 3;           # Sets $foofoo
$name-&gt;[0] = 4;             # Sets $foo[0]
@$name = ();                # Clears @foo
&amp;$name();                   # Calls &amp;foo()
$pack = &quot;THAT&quot;;
${&quot;${pack}::$name&quot;} = 5;    # Sets $THAT::foo without eval</code></pre>

<p>This is powerful, and slightly dangerous, in that it&#39;s possible to intend (with the utmost sincerity) to use a hard reference, and accidentally use a symbolic reference instead. To protect against that, you can say</p>

<pre><code>use strict &#39;refs&#39;;</code></pre>

<p>and then only hard references will be allowed for the rest of the enclosing block. An inner block may countermand that with</p>

<pre><code>no strict &#39;refs&#39;;</code></pre>

<p>Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren&#39;t in a symbol table, and thus are invisible to this mechanism. For example:</p>

<pre><code>local $value = 10;
$ref = &quot;value&quot;;
{
    my $value = 20;
    print $$ref;
}</code></pre>

<p>This will still print 10, not 20. Remember that local() affects package variables, which are all &quot;global&quot; to the package.</p>

<h2 id="Not-so-symbolic-references"><a class="permalink" href="perlref.html#Not-so-symbolic-references">#</a><a id="Not"></a>Not-so-symbolic references</h2>

<p>Brackets around a symbolic reference can simply serve to isolate an identifier or variable name from the rest of an expression, just as they always have within a string. For example,</p>

<pre><code>$push = &quot;pop on &quot;;
print &quot;${push}over&quot;;</code></pre>

<p>has always meant to print &quot;pop on over&quot;, even though push is a reserved word. This is generalized to work the same without the enclosing double quotes, so that</p>

<pre><code>print ${push} . &quot;over&quot;;</code></pre>

<p>and even</p>

<pre><code>print ${ push } . &quot;over&quot;;</code></pre>

<p>will have the same effect. This construct is <i>not</i> considered to be a symbolic reference when you&#39;re using strict refs:</p>

<pre><code>use strict &#39;refs&#39;;
${ bareword };      # Okay, means $bareword.
${ &quot;bareword&quot; };    # Error, symbolic reference.</code></pre>

<p>Similarly, because of all the subscripting that is done using single words, the same rule applies to any bareword that is used for subscripting a hash. So now, instead of writing</p>

<pre><code>$hash{ &quot;aaa&quot; }{ &quot;bbb&quot; }{ &quot;ccc&quot; }</code></pre>

<p>you can write just</p>

<pre><code>$hash{ aaa }{ bbb }{ ccc }</code></pre>

<p>and not worry about whether the subscripts are reserved words. In the rare event that you do wish to do something like</p>

<pre><code>$hash{ shift }</code></pre>

<p>you can force interpretation as a reserved word by adding anything that makes it more than a bareword:</p>

<pre><code>$hash{ shift() }
$hash{ +shift }
$hash{ shift @_ }</code></pre>

<p>The <code>use warnings</code> pragma or the <b>-w</b> switch will warn you if it interprets a reserved word as a string. But it will no longer warn you about using lowercase words, because the string is effectively quoted.</p>

<h2 id="Pseudo-hashes:-Using-an-array-as-a-hash"><a class="permalink" href="perlref.html#Pseudo-hashes:-Using-an-array-as-a-hash">#</a><a id="Pseudo"></a>Pseudo-hashes: Using an array as a hash   </h2>

<p>Pseudo-hashes have been removed from Perl. The &#39;fields&#39; pragma remains available.</p>

<h2 id="Function-Templates"><a class="permalink" href="perlref.html#Function-Templates">#</a><a id="Function"></a>Function Templates        </h2>

<p>As explained above, an anonymous function with access to the lexical variables visible when that function was compiled, creates a closure. It retains access to those variables even though it doesn&#39;t get run until later, such as in a signal handler or a Tk callback.</p>

<p>Using a closure as a function template allows us to generate many functions that act similarly. Suppose you wanted functions named after the colors that generated HTML font changes for the various colors:</p>

<pre><code>print &quot;Be &quot;, red(&quot;careful&quot;), &quot;with that &quot;, green(&quot;light&quot;);</code></pre>

<p>The red() and green() functions would be similar. To create these, we&#39;ll assign a closure to a typeglob of the name of the function we&#39;re trying to build.</p>

<pre><code>@colors = qw(red blue green yellow orange purple violet);
for my $name (@colors) {
    no strict &#39;refs&#39;;       # allow symbol table manipulation
    *$name = *{uc $name} = sub { &quot;&lt;FONT COLOR=&#39;$name&#39;&gt;@_&lt;/FONT&gt;&quot; };
}</code></pre>

<p>Now all those different functions appear to exist independently. You can call red(), RED(), blue(), BLUE(), green(), etc. This technique saves on both compile time and memory use, and is less error-prone as well, since syntax checks happen at compile time. It&#39;s critical that any variables in the anonymous subroutine be lexicals in order to create a proper closure. That&#39;s the reasons for the <code>my</code> on the loop iteration variable.</p>

<p>This is one of the only places where giving a prototype to a closure makes much sense. If you wanted to impose scalar context on the arguments of these functions (probably not a wise idea for this particular example), you could have written it this way instead:</p>

<pre><code>*$name = sub ($) { &quot;&lt;FONT COLOR=&#39;$name&#39;&gt;$_[0]&lt;/FONT&gt;&quot; };</code></pre>

<p>However, since prototype checking happens at compile time, the assignment above happens too late to be of much use. You could address this by putting the whole loop of assignments within a BEGIN block, forcing it to occur during compilation.</p>

<p>Access to lexicals that change over time--like those in the <code>for</code> loop above, basically aliases to elements from the surrounding lexical scopes-- only works with anonymous subs, not with named subroutines. Generally said, named subroutines do not nest properly and should only be declared in the main package scope.</p>

<p>This is because named subroutines are created at compile time so their lexical variables get assigned to the parent lexicals from the first execution of the parent block. If a parent scope is entered a second time, its lexicals are created again, while the nested subs still reference the old ones.</p>

<p>Anonymous subroutines get to capture each time you execute the <code>sub</code> operator, as they are created on the fly. If you are accustomed to using nested subroutines in other programming languages with their own private variables, you&#39;ll have to work at it a bit in Perl. The intuitive coding of this type of thing incurs mysterious warnings about &quot;will not stay shared&quot; due to the reasons explained above. For example, this won&#39;t work:</p>

<pre><code>sub outer {
    my $x = $_[0] + 35;
    sub inner { return $x * 19 }   # WRONG
    return $x + inner();
}</code></pre>

<p>A work-around is the following:</p>

<pre><code>sub outer {
    my $x = $_[0] + 35;
    local *inner = sub { return $x * 19 };
    return $x + inner();
}</code></pre>

<p>Now inner() can only be called from within outer(), because of the temporary assignments of the anonymous subroutine. But when it does, it has normal access to the lexical variable $x from the scope of outer() at the time outer is invoked.</p>

<p>This has the interesting effect of creating a function local to another function, something not normally supported in Perl.</p>

<h2 id="Postfix-Dereference-Syntax"><a class="permalink" href="perlref.html#Postfix-Dereference-Syntax">#</a><a id="Postfix"></a>Postfix Dereference Syntax</h2>

<p>Beginning in v5.20.0, a postfix syntax for using references is available. It behaves as described in <a href="perlref.html#Using-References">&quot;Using References&quot;</a>, but instead of a prefixed sigil, a postfixed sigil-and-star is used.</p>

<p>For example:</p>

<pre><code>$r = \@a;
@b = $r-&gt;@*; # equivalent to @$r or @{ $r }

$r = [ 1, [ 2, 3 ], 4 ];
$r-&gt;[1]-&gt;@*;  # equivalent to @{ $r-&gt;[1] }</code></pre>

<p>In Perl 5.20 and 5.22, this syntax must be enabled with <code>use feature &#39;postderef&#39;</code>. As of Perl 5.24, no feature declarations are required to make it available.</p>

<p>Postfix dereference should work in all circumstances where block (circumfix) dereference worked, and should be entirely equivalent. This syntax allows dereferencing to be written and read entirely left-to-right. The following equivalencies are defined:</p>

<pre><code>$sref-&gt;$*;  # same as  ${ $sref }
$aref-&gt;@*;  # same as  @{ $aref }
$aref-&gt;$#*; # same as $#{ $aref }
$href-&gt;%*;  # same as  %{ $href }
$cref-&gt;&amp;*;  # same as  &amp;{ $cref }
$gref-&gt;**;  # same as  *{ $gref }</code></pre>

<p>Note especially that <code>$cref-&gt;&amp;*</code> is <i>not</i> equivalent to <code>$cref-&gt;()</code>, and can serve different purposes.</p>

<p>Glob elements can be extracted through the postfix dereferencing feature:</p>

<pre><code>$gref-&gt;*{SCALAR}; # same as *{ $gref }{SCALAR}</code></pre>

<p>Postfix array and scalar dereferencing <i>can</i> be used in interpolating strings (double quotes or the <code>qq</code> operator), but only if the <code>postderef_qq</code> feature is enabled.</p>

<h2 id="Postfix-Reference-Slicing"><a class="permalink" href="perlref.html#Postfix-Reference-Slicing">#</a><a id="Postfix1"></a>Postfix Reference Slicing</h2>

<p>Value slices of arrays and hashes may also be taken with postfix dereferencing notation, with the following equivalencies:</p>

<pre><code>$aref-&gt;@[ ... ];  # same as @$aref[ ... ]
$href-&gt;@{ ... };  # same as @$href{ ... }</code></pre>

<p>Postfix key/value pair slicing, added in 5.20.0 and documented in <a href="perldata.html#Key%2FValue-Hash-Slices">the Key/Value Hash Slices section of perldata</a>, also behaves as expected:</p>

<pre><code>$aref-&gt;%[ ... ];  # same as %$aref[ ... ]
$href-&gt;%{ ... };  # same as %$href{ ... }</code></pre>

<p>As with postfix array, postfix value slice dereferencing <i>can</i> be used in interpolating strings (double quotes or the <code>qq</code> operator), but only if the <code>postderef_qq</code> <a href="feature.html">feature</a> is enabled.</p>

<h2 id="Assigning-to-References"><a class="permalink" href="perlref.html#Assigning-to-References">#</a><a id="Assigning"></a>Assigning to References</h2>

<p>Beginning in v5.22.0, the referencing operator can be assigned to. It performs an aliasing operation, so that the variable name referenced on the left-hand side becomes an alias for the thing referenced on the right-hand side:</p>

<pre><code>\$a = \$b; # $a and $b now point to the same scalar
\&amp;foo = \&amp;bar; # foo() now means bar()</code></pre>

<p>This syntax must be enabled with <code>use feature &#39;refaliasing&#39;</code>. It is experimental, and will warn by default unless <code>no warnings &#39;experimental::refaliasing&#39;</code> is in effect.</p>

<p>These forms may be assigned to, and cause the right-hand side to be evaluated in scalar context:</p>

<pre><code>\$scalar
\@array
\%hash
\&amp;sub
\my $scalar
\my @array
\my %hash
\state $scalar # or @array, etc.
\our $scalar   # etc.
\local $scalar # etc.
\local our $scalar # etc.
\$some_array[$index]
\$some_hash{$key}
\local $some_array[$index]
\local $some_hash{$key}
condition ? \$this : \$that[0] # etc.</code></pre>

<p>Slicing operations and parentheses cause the right-hand side to be evaluated in list context:</p>

<pre><code>\@array[5..7]
(\@array[5..7])
\(@array[5..7])
\@hash{&#39;foo&#39;,&#39;bar&#39;}
(\@hash{&#39;foo&#39;,&#39;bar&#39;})
\(@hash{&#39;foo&#39;,&#39;bar&#39;})
(\$scalar)
\($scalar)
\(my $scalar)
\my($scalar)
(\@array)
(\%hash)
(\&amp;sub)
\(&amp;sub)
\($foo, @bar, %baz)
(\$foo, \@bar, \%baz)</code></pre>

<p>Each element on the right-hand side must be a reference to a datum of the right type. Parentheses immediately surrounding an array (and possibly also <code>my</code>/<code>state</code>/<code>our</code>/<code>local</code>) will make each element of the array an alias to the corresponding scalar referenced on the right-hand side:</p>

<pre><code>\(@a) = \(@b); # @a and @b now have the same elements
\my(@a) = \(@b); # likewise
\(my @a) = \(@b); # likewise
push @a, 3; # but now @a has an extra element that @b lacks
\(@a) = (\$a, \$b, \$c); # @a now contains $a, $b, and $c</code></pre>

<p>Combining that form with <code>local</code> and putting parentheses immediately around a hash are forbidden (because it is not clear what they should do):</p>

<pre><code>\local(@array) = foo(); # WRONG
\(%hash)       = bar(); # WRONG</code></pre>

<p>Assignment to references and non-references may be combined in lists and conditional ternary expressions, as long as the values on the right-hand side are the right type for each element on the left, though this may make for obfuscated code:</p>

<pre><code>(my $tom, \my $dick, \my @harry) = (\1, \2, [1..3]);
# $tom is now \1
# $dick is now 2 (read-only)
# @harry is (1,2,3)

my $type = ref $thingy;
($type ? $type eq &#39;ARRAY&#39; ? \@foo : \$bar : $baz) = $thingy;</code></pre>

<p>The <code>foreach</code> loop can also take a reference constructor for its loop variable, though the syntax is limited to one of the following, with an optional <code>my</code>, <code>state</code>, or <code>our</code> after the backslash:</p>

<pre><code>\$s
\@a
\%h
\&amp;c</code></pre>

<p>No parentheses are permitted. This feature is particularly useful for arrays-of-arrays, or arrays-of-hashes:</p>

<pre><code>foreach \my @a (@array_of_arrays) {
    frobnicate($a[0], $a[-1]);
}

foreach \my %h (@array_of_hashes) {
    $h{gelastic}++ if $h{type} eq &#39;funny&#39;;
}</code></pre>

<p><b>CAVEAT:</b> Aliasing does not work correctly with closures. If you try to alias lexical variables from an inner subroutine or <code>eval</code>, the aliasing will only be visible within that inner sub, and will not affect the outer subroutine where the variables are declared. This bizarre behavior is subject to change.</p>

<h2 id="Declaring-a-Reference-to-a-Variable"><a class="permalink" href="perlref.html#Declaring-a-Reference-to-a-Variable">#</a><a id="Declaring"></a>Declaring a Reference to a Variable</h2>

<p>Beginning in v5.26.0, the referencing operator can come after <code>my</code>, <code>state</code>, <code>our</code>, or <code>local</code>. This syntax must be enabled with <code>use feature &#39;declared_refs&#39;</code>. It is experimental, and will warn by default unless <code>no warnings &#39;experimental::refaliasing&#39;</code> is in effect.</p>

<p>This feature makes these:</p>

<pre><code>my \$x;
our \$y;</code></pre>

<p>equivalent to:</p>

<pre><code>\my $x;
\our $x;</code></pre>

<p>It is intended mainly for use in assignments to references (see <a href="perlref.html#Assigning-to-References">&quot;Assigning to References&quot;</a>, above). It also allows the backslash to be used on just some items in a list of declared variables:</p>

<pre><code>my ($foo, \@bar, \%baz); # equivalent to:  my $foo, \my(@bar, %baz);</code></pre>

<h1 id="WARNING:-Don&#39;t-use-references-as-hash-keys"><a class="permalink" href="perlref.html#WARNING:-Don&#39;t-use-references-as-hash-keys">#</a><a id="WARNING"></a><a id="WARNING:-Dont-use-references-as-hash-keys"></a>WARNING: Don&#39;t use references as hash keys  </h1>

<p>You may not (usefully) use a reference as the key to a hash. It will be converted into a string:</p>

<pre><code>$x{ \$a } = $a;</code></pre>

<p>If you try to dereference the key, it won&#39;t do a hard dereference, and you won&#39;t accomplish what you&#39;re attempting. You might want to do something more like</p>

<pre><code>$r = \@a;
$x{ $r } = $r;</code></pre>

<p>And then at least you can use the values(), which will be real refs, instead of the keys(), which won&#39;t.</p>

<p>The standard Tie::RefHash module provides a convenient workaround to this.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="perlref.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p>Besides the obvious documents, source code can be instructive. Some pathological examples of the use of references can be found in the <i>t/op/ref.t</i> regression test in the Perl source directory.</p>

<p>See also <a href="perldsc.html">perldsc</a> and <a href="perllol.html">perllol</a> for how to use references to create complex data structures, and <a href="perlootut.html">perlootut</a> and <a href="perlobj.html">perlobj</a> for how to use them to create objects.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
